package com.xuzhiguang.lightnat.client.proxy.handler;

import com.xuzhiguang.lightnat.common.manager.ProxyChannelManager;
import com.xuzhiguang.lightnat.common.manager.TransferChannelManager;
import com.xuzhiguang.lightnat.common.message.NatMessage;
import com.xuzhiguang.lightnat.common.serializer.SerializerTypeEnum;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class TransferHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

        log.debug("proxy transfer. channel:{}", ctx.channel());

        Long transferId = ProxyChannelManager.getTransferId(ctx.channel());

        if (transferId == null) {
            log.warn("transferId is null. channel id:{}", ctx.channel());
            return;
        }

        Channel transferChannel = TransferChannelManager.getChannel(transferId);
        if (transferChannel == null) {
            log.warn("transferChannel is null. transferId:{}", transferId);
            return;
        }

        byte[] bodyData = new byte[msg.readableBytes()];
        msg.readBytes(bodyData);
        NatMessage natMessage = new NatMessage(bodyData, SerializerTypeEnum.BYTE.getType());

        // transfer 将数据转发到 server
        transferChannel.writeAndFlush(natMessage);
    }

}
